import { NestFactory } from '@nestjs/core';
import * as nunjucks from 'nunjucks';
import { ConfigService } from '@nestjs/config';
import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ResponseInterceptor } from '@/common/interceptors/response.interceptor';
import { AppModule } from './app.module';
import { join } from 'node:path';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const configService = app.get(ConfigService);

  app.setGlobalPrefix('api');
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true, // 剔除 DTO 中未声明的字段
      forbidNonWhitelisted: true, // 多余字段时抛出异常
      transform: true, // 自动类型转换
      transformOptions: {
        enableImplicitConversion: true, // 自动将字符串转为 number/boolean
      },
      exceptionFactory: (errors) => {
        const messages = errors.map((err) => ({
          field: err.property,
          constraints: Object.values(err.constraints || {}),
        }));
        return new BadRequestException({
          errno: 400,
          message: '参数验证失败',
          errors: messages,
        });
      },
    }),
  );
  app.useGlobalInterceptors(new ResponseInterceptor());
  app.useStaticAssets(join(__dirname, '..', 'upload'), {
    prefix: '/upload',
  });
  app.useStaticAssets(join(__dirname, '..', 'view'), {
    prefix: '/view',
  });
  const viewsPath = join(__dirname, '..', 'view');
  app.setBaseViewsDir(viewsPath);
  nunjucks.configure(viewsPath, {
    autoescape: true,
    express: app.getHttpAdapter().getInstance(),
  });
  app.setViewEngine('nj');
  await app.listen(configService.get<number>('port'));
  return app;
}
bootstrap().then((app) => {
  console.log(
    `Application is running on: ${app.get(ConfigService).get('port')}`,
  );
});
